const express = require('express');
const path = require('path');
const fs = require('fs');
const app = express();
const http = require('http');
const server = http.createServer(app);
const bodyParser = require('body-parser');
const dbr = require("barcode4nodejs")
dbr.initLicense(
    "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==",
)

app.use(express.static('public'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

app.post('/readbarcode', async (req, res) => {
    const data = req.body;
    let chunks = [];

    req.on('data', (chunk) => {
        chunks.push(chunk);
    });

    req.on('end', () => {
        let nodeBuffer = Buffer.concat(chunks);
        dbr.decodeFileStreamAsync(nodeBuffer, nodeBuffer.length, dbr.formats.QRCode).then((results) => {
            let output = '';
            let index = 0;
            for (result of results) {
                output += index + ': ' + result['value'] + ' ';
                index += 1;
            }
            res.status(200).send(output);
        });
    });
});

// Start the server
const port = process.env.PORT || 3000;

server.listen(port, '0.0.0.0', () => {
    host = server.address().address;
    console.log(`Server running at http://0.0.0.0:${port}/`);
});
